<?php
namespace UserApi\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class SubscribeApiController extends AbstractRestfulController
{
    public function getList()
    {
		header('Access-Control-Allow-Origin: *');
		$data=array();
		$subscribeTable=$this->getServiceLocator()->get('Models\Model\SubscribeFactory');
		$all_lists = $subscribeTable->allsubscribers();
		if(count($all_lists)!=0){
			foreach($all_lists as $allsubscribers){
				$data[]=$allsubscribers;
			}
			return new JsonModel(array(
				'data'=> json_encode($data),
			));
		}else{
			return new JsonModel(array(
				'data'=> 'no data',
			));
		}
    }
    public function get($data)
    {		
		
    }
    public function create($s_eamil)
    {
		header('Access-Control-Allow-Origin: *');
		global $subscribemailsubject;				
		global $subscribemailMessage;
		$subscribeTable=$this->getServiceLocator()->get('Models\Model\SubscribeFactory');			
		if(!empty($s_eamil['email'])){
			$check_email_status = $subscribeTable->checkEmail($s_eamil['email'])->toarray();
			if(count($check_email_status)==0){
				
				$add_subscriber = $subscribeTable->addSubscribe($s_eamil['email']);
				$to   		 = $s_eamil['email'];
				$body  		 = $subscribemailMessage;
				$body  		 = str_replace("<FULLNAME>",$s_eamil['email'], $body);
				$sentemail   = sendMail($to,$subscribemailsubject,$body);
				
				if($sentemail){
					if($add_subscriber!=0){
						return new JsonModel(array(
							'success'	=> 'success',
							'value'		=> '1',
						));
					}
				}else{
					return new JsonModel(array(
						'status'	=> 'Mail Not Sent Successfully',
						'value'		=> '0',
					));
				}
			}else{
				return new JsonModel(array(
					'status'	=> 'Your already subscribed user',
					'value'		=> '0',
				));
			}
		}else{
			return new JsonModel(array(					
			  'return'=> 'nodata',
			));
		}
    }
    public function update($id, $s_eamil)
    {
		header('Access-Control-Allow-Origin: *');
		$subscribeTable=$this->getServiceLocator()->get('Models\Model\SubscribeFactory');	
		if(!empty($s_eamil['email'])){
			$check_email_status = $subscribeTable->checkEmail($s_eamil['email']);
			if($check_email_status==1){
				if($id==0){
					$status=0;
				}else if($id==1){
					$status=1;
				}
				$add_subscriber = $subscribeTable->unsubscribe($status,$s_eamil['email']);
				if($add_subscriber!=0){
					return new JsonModel(array(
						'success'=> 'success',
					));
				}else{
					return new JsonModel(array(
						'status'=> 'not_success',
					));
				}
			}else{
				return new JsonModel(array(
					'status'=> 'email_is_not_exists',
				));
			}
		}else{
			return new JsonModel(array(					
			  'return'=> 'nodata',
			));
		}
    }
    public function delete($id)
    {
       
    }
}